// puzzle-game.js - 单词拼图游戏逻辑
const { playRightSound, playWrongSound, playClickSound } = require('../../../../utils/audioUtils.js');
const storageManager = require('../../../../manager/storageManager').getInstance();

Page({
  data: {
    score: 0,
    currentLevel: 1,
    totalLevels: 8,
    currentWord: null,
    answerSlots: [],
    puzzlePieces: [],
    hintsLeft: 3,
    totalHintsUsed: 0,
    completedLevels: 0,
    correctAttempts: 0,
    wrongAttempts: 0,
    gameOver: false,
    resultIcon: '',
    resultTitle: '',
    stars: 0,
    accuracy: 0,
    showToast: false,
    toastMessage: '',
    toastIcon: '',
    toastBg: '#4caf50',
    showSuccess: false,
    wordsList: []
  },

  onLoad: function() {
    // 初始化数据管理器 - 使用全局实例
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.magicCoinManager = app.getMagicCoinManager();
    this.initGame();
  },

  // 初始化游戏
  initGame: function() {
    const wordsDict = this.wordDataManager.getAllWords();
    const allWords = Object.values(wordsDict).filter(word => 
      word && word.english && word.chinese && word.english.length >= 4 && word.english.length <= 8
    );

    if (allWords.length < 8) {
      wx.showToast({
        title: '单词数量不足',
        icon: 'none'
      });
      return;
    }

    const wordsList = this.shuffleArray(allWords).slice(0, 8);

    this.setData({
      wordsList,
      currentLevel: 1,
      score: 0,
      hintsLeft: 3,
      totalHintsUsed: 0,
      completedLevels: 0,
      correctAttempts: 0,
      wrongAttempts: 0,
      gameOver: false
    });

    this.loadLevel(0);
  },

  // 加载关卡
  loadLevel: function(index) {
    const word = this.data.wordsList[index];
    const letters = word.english.toUpperCase().split('');
    
    // 创建答案槽位
    const answerSlots = letters.map(() => ({
      filled: false,
      letter: '',
      correct: false
    }));

    // 创建拼图块（打乱顺序）
    const shuffledLetters = this.shuffleArray([...letters]);
    const puzzlePieces = shuffledLetters.map((letter, i) => ({
      letter,
      used: false,
      animation: null
    }));


    this.setData({
      currentWord: { ...word },
      answerSlots,
      puzzlePieces
    });
  },

  // 选择拼图块
  selectPiece: function(e) {
    // 播放点击音效
    playClickSound();
    
    const index = e.currentTarget.dataset.index;
    const piece = this.data.puzzlePieces[index];

    if (piece.used) return;

    // 找到第一个空槽位
    const emptySlotIndex = this.data.answerSlots.findIndex(slot => !slot.filled);
    if (emptySlotIndex === -1) return;

    // 更新拼图块状态
    const puzzlePieces = [...this.data.puzzlePieces];
    puzzlePieces[index].used = true;

    // 更新槽位
    const answerSlots = [...this.data.answerSlots];
    answerSlots[emptySlotIndex] = {
      filled: true,
      letter: piece.letter,
      pieceIndex: index,
      correct: false
    };

    this.setData({ puzzlePieces, answerSlots });
  },

  // 从槽位移除
  removeFromSlot: function(e) {
    // 播放点击音效
    playClickSound();
    
    const slotIndex = e.currentTarget.dataset.index;
    const slot = this.data.answerSlots[slotIndex];

    if (!slot.filled) return;

    // 恢复拼图块
    const puzzlePieces = [...this.data.puzzlePieces];
    puzzlePieces[slot.pieceIndex].used = false;

    // 清空槽位
    const answerSlots = [...this.data.answerSlots];
    answerSlots[slotIndex] = {
      filled: false,
      letter: '',
      correct: false
    };

    this.setData({ puzzlePieces, answerSlots });
  },

  // 清空答案
  clearAnswer: function() {
    // 播放点击音效
    playClickSound();
    
    const puzzlePieces = this.data.puzzlePieces.map(piece => ({
      ...piece,
      used: false
    }));

    const answerSlots = this.data.answerSlots.map(() => ({
      filled: false,
      letter: '',
      correct: false
    }));

    this.setData({ puzzlePieces, answerSlots });
  },

  // 使用提示
  useHint: function() {
    // 播放点击音效
    playClickSound();
    
    if (this.data.hintsLeft <= 0) return;

    const correctWord = this.data.currentWord.english.toUpperCase();
    
    // 找到第一个未填或错误的位置
    let hintIndex = -1;
    for (let i = 0; i < correctWord.length; i++) {
      if (!this.data.answerSlots[i].filled || 
          this.data.answerSlots[i].letter !== correctWord[i]) {
        hintIndex = i;
        break;
      }
    }

    if (hintIndex === -1) return;

    // 如果该位置已有字母，先移除
    if (this.data.answerSlots[hintIndex].filled) {
      const puzzlePieces = [...this.data.puzzlePieces];
      puzzlePieces[this.data.answerSlots[hintIndex].pieceIndex].used = false;
      this.setData({ puzzlePieces });
    }

    // 找到正确的拼图块
    const correctLetter = correctWord[hintIndex];
    const puzzlePieces = [...this.data.puzzlePieces];
    const pieceIndex = puzzlePieces.findIndex(p => p.letter === correctLetter && !p.used);

    if (pieceIndex !== -1) {
      puzzlePieces[pieceIndex].used = true;
      
      const answerSlots = [...this.data.answerSlots];
      answerSlots[hintIndex] = {
        filled: true,
        letter: correctLetter,
        pieceIndex,
        correct: true
      };

      this.setData({
        puzzlePieces,
        answerSlots,
        hintsLeft: this.data.hintsLeft - 1,
        totalHintsUsed: this.data.totalHintsUsed + 1
      });

      this.showToast('💡', '提示已使用', '#ff9800');
    }
  },

  // 检查答案
  checkAnswer: function() {
    // 播放点击音效
    playClickSound();
    
    const userAnswer = this.data.answerSlots.map(slot => slot.letter).join('');
    const correctAnswer = this.data.currentWord.english.toUpperCase();

    if (userAnswer.length !== correctAnswer.length) {
      this.showToast('⚠️', '请完成拼图', '#ff9800');
      return;
    }

    if (userAnswer === correctAnswer) {
      this.handleCorrectAnswer();
    } else {
      this.handleWrongAnswer();
    }
  },

  // 处理正确答案
  handleCorrectAnswer: function() {
    const baseScore = 100;
    const hintPenalty = (3 - this.data.hintsLeft) * 10;
    const levelBonus = this.data.currentLevel * 20;
    const score = this.data.score + baseScore - hintPenalty + levelBonus;
    const completedLevels = this.data.completedLevels + 1;

    // 标记所有槽位为正确
    const answerSlots = this.data.answerSlots.map(slot => ({
      ...slot,
      correct: true
    }));

    this.setData({
      answerSlots,
      score,
      completedLevels,
      correctAttempts: this.data.correctAttempts + 1,
      showSuccess: true
    });

    playRightSound();
    wx.vibrateShort({ type: 'medium' });

    setTimeout(() => {
      this.setData({ showSuccess: false });
      
      if (this.data.currentLevel >= this.data.totalLevels) {
        this.endGame();
      } else {
        this.nextLevel();
      }
    }, 1500);
  },

  // 处理错误答案
  handleWrongAnswer: function() {
    const score = Math.max(0, this.data.score - 20);

    this.setData({
      score,
      wrongAttempts: this.data.wrongAttempts + 1
    });

    playWrongSound();
    wx.vibrateShort({ type: 'heavy' });
    this.showToast('✗', '答错了，再试一次！', '#f44336');

    setTimeout(() => {
      this.clearAnswer();
    }, 1000);
  },

  // 下一关
  nextLevel: function() {
    const currentLevel = this.data.currentLevel + 1;
    this.setData({ 
      currentLevel,
      hintsLeft: 3
    });
    this.loadLevel(currentLevel - 1);
  },

  // 打乱数组
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 显示提示信息
  showToast: function(icon, message, bg) {
    this.setData({
      showToast: true,
      toastIcon: icon,
      toastMessage: message,
      toastBg: bg
    });

    setTimeout(() => {
      this.setData({ showToast: false });
    }, 1000);
  },

  // 结束游戏
  endGame: function() {
    const totalAttempts = this.data.correctAttempts + this.data.wrongAttempts;
    const accuracy = totalAttempts > 0 ? Math.round((this.data.correctAttempts / totalAttempts) * 100) : 0;
    
    let stars = 0;
    let resultIcon = '';
    let resultTitle = '';

    if (this.data.completedLevels >= 8 && this.data.totalHintsUsed <= 5) {
      stars = 3;
      resultIcon = '🏆';
      resultTitle = '拼图大师！';
    } else if (this.data.completedLevels >= 6) {
      stars = 2;
      resultIcon = '🌟';
      resultTitle = '表现不错！';
    } else {
      stars = 1;
      resultIcon = '👍';
      resultTitle = '继续加油！';
    }

    // 奖励魔法币
    const coins = stars * 10;
    this.magicCoinManager.addMagicCoins(coins, `单词拼图游戏 - ${stars}星`);

    // 保存游戏记录
    this.saveGameRecord(stars);

    this.setData({
      gameOver: true,
      accuracy,
      stars,
      resultIcon,
      resultTitle
    });
  },

  // 保存游戏记录
  saveGameRecord: function(stars) {
    try {
      const gameStats = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS) || {
        totalGamesPlayed: 0,
        totalStars: 0,
        highScore: 0,
        matching: { played: 0, bestScore: 0 },
        scramble: { played: 0, bestScore: 0 },
        memory: { played: 0, bestScore: 0 },
        chain: { played: 0, bestScore: 0 },
        typing: { played: 0, bestScore: 0 },
        puzzle: { played: 0, bestScore: 0 }
      };

      gameStats.totalGamesPlayed += 1;
      gameStats.totalStars += stars;
      gameStats.highScore = Math.max(gameStats.highScore, this.data.score);
      gameStats.puzzle.played += 1;
      gameStats.puzzle.bestScore = Math.max(gameStats.puzzle.bestScore, this.data.score);

      storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS, gameStats);

      const recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      recentGames.unshift({
        id: Date.now(),
        gameName: '单词拼图',
        icon: '🧩',
        score: this.data.score,
        stars,
        timestamp: new Date().toISOString()
      });

      storageManager.setStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES, recentGames.slice(0, 10));
    } catch (error) {
      console.error('保存游戏记录失败:', error);
    }
  },

  // 重新开始游戏
  restartGame: function() {
    // 播放点击音效
    playClickSound();
    this.initGame();
  },

  // 返回
  goBack: function() {
    // 播放点击音效
    playClickSound();
    wx.navigateBack();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: `我在单词拼图游戏中完成了${this.data.completedLevels}个关卡！快来挑战吧！`,
      path: '/pages/challenge/word-games/puzzle-game/puzzle-game',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在单词拼图游戏中完成了${this.data.completedLevels}个关卡！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});
